package com.ae.content.service.impl;

import com.ae.content.dto.HeartDTO;
import com.ae.content.dto.HostInfo;
import com.ae.content.util.HttpClientUtil;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.SecureRandom;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Component
public class AdminListener {
    private static final String URL = "http://192.168.110.95:7002";

     private static final String CHAR_UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final String CHAR_LOWER = CHAR_UPPER.toLowerCase();
    private static final String NUMBER = "0123456789";
    private static final String SPECIAL_CHAR = "!@#$%^&*()";
    private static final int PASSWORD_LENGTH = 8; // 基础字符串长度（不包含特殊字符）
    private static final Random RANDOM = new SecureRandom();

    static Map<String, String> map = new HashMap<>();

    // 每隔60s秒执行一次
//    @Scheduled(fixedRate = 60000)
    public void fixedRateTask() {
        System.out.println("---------------------每60s执行一次定时任务---------------------");
        try {
            String command = "cmd.exe /c netstat -n | findstr :3389";
            Process process = Runtime.getRuntime().exec(command);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.contains("ESTABLISHED")) {
                    String[] parts = line.split("\\s+");
                    for(String s : parts) {
                        System.out.println(s);
                    }
                    String remoteAddress = parts[3]; // 通常连接的IP和端口在第3部分，如 192.168.1.4:3389
                    System.out.println("remoteAddress:" + remoteAddress.toString());
                    System.out.println("远程桌面连接来自IP: " + remoteAddress.split(":")[0]);
                    // 获取本机的IP地址3
                    HeartDTO heartDTO = new HeartDTO();
                    heartDTO.setRemoteAddress(remoteAddress.split(":")[0]);
                    // 如果如果用户登出的话 则修改密码
                    if(StringUtils.isNotBlank(remoteAddress.split(":")[0])) {
                        System.out.println("--------------用户正在使用中--------------");
//                        // 返回前修改密码
//                        try {
//                            String randomStr = generateCustomRandomString();
//                            String currentUsername = System.getProperty("user.name"); // 获取当前用户名
//                            System.out.println("currentUsername:" + currentUsername);
//                            String command2 = "net user " + currentUsername + " " + randomStr; // 替换<newPassword>为新密码，/domain仅在域环境中使用
//                            System.out.println("command2:" + command2);
//                            Process process2 = Runtime.getRuntime().exec(command2);
//                            int exitCode = process2.waitFor();
//                            if (exitCode == 0) {
//                                System.out.println("密码修改成功");
//                            } else {
//                                System.err.println("密码修改失败，错误代码：" + exitCode);
//                                // 可以进一步读取错误流以获取具体错误信息
//                            }
//                            heartDTO.setHostPwd(randomStr);
//                            // 调用http接口写数据
//                            HostInfo hostInfo = new HostInfo();
//                            hostInfo.setHostaddress(getHostAddress());
//                            hostInfo.setRemoteaddress(remoteAddress);
//                            hostInfo.setHostpwd(randomStr);
//                            HttpClientUtil.doPost("http://192.168.2.88:8082/ippassword/saveorupdate", JSON.toJSONString(hostInfo));
//                            System.out.println("remote login update pwd success");
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
                    }
                }
            }
            process.waitFor();
            // 调用http接口写数据
//            HostInfo hostInfo = new HostInfo();
//            hostInfo.setHostaddress(getHostAddress());
//            hostInfo.setRemoteaddress("");
//            // 修改密码
//            String randomStr = generateCustomRandomString();
//            String currentUsername = System.getProperty("user.name"); // 获取当前用户名
//            System.out.println("currentUsername:" + currentUsername);
//            String command2 = "net user " + currentUsername + " " + randomStr; // 替换<newPassword>为新密码，/domain仅在域环境中使用
//            System.out.println("command2:" + command2);
//            Process process2 = Runtime.getRuntime().exec(command2);
//            int exitCode = process2.waitFor();
//            if (exitCode == 0) {
//                System.out.println("密码修改成功");
//            } else {
//                System.err.println("密码修改失败，错误代码：" + exitCode);
//                // 可以进一步读取错误流以获取具体错误信息
//            }
//            hostInfo.setHostpwd(randomStr);
//            System.out.println(JSON.toJSONString(hostInfo));
//            HttpClientUtil.doPost("http://192.168.2.88:8082/ippassword/saveorupdate", JSON.toJSONString(hostInfo));
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }


    private static String generateCustomRandomString() {
        StringBuilder sb = new StringBuilder(PASSWORD_LENGTH + 1); // 多一个位置留给特殊字符

        // 保证第一个字符是大写字母
        sb.append(CHAR_UPPER.charAt(RANDOM.nextInt(CHAR_UPPER.length())));

        // 紧接着一个小写字母
        sb.append(CHAR_LOWER.charAt(RANDOM.nextInt(CHAR_LOWER.length())));

        // 拼接数字，这里随机决定添加多少个数字，但至少一个
        int numDigits = RANDOM.nextInt(3) + 1; // 至少一个数字，最多三个
        for (int i = 0; i < numDigits; i++) {
            sb.append(NUMBER.charAt(RANDOM.nextInt(NUMBER.length())));
        }

        // 保持总长度不变，如果数字添加过多，则减少基础字符串的长度
        int remainingChars = Math.max(0, PASSWORD_LENGTH - numDigits - 2); // 减去已固定的字符数
        for (int i = 0; i < remainingChars; i++) {
            sb.append(CHAR_LOWER.charAt(RANDOM.nextInt(CHAR_LOWER.length())));
        }

        // 以特殊字符结尾
        sb.append(SPECIAL_CHAR.charAt(RANDOM.nextInt(SPECIAL_CHAR.length())));

        return sb.toString();
    }

    private String getHostAddress() {
        // 获取本机的IP地址
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface networkInterface = interfaces.nextElement();
                // 过滤掉 loopback 地址（即 127.0.0.1）和非激活的接口
                if (networkInterface.isLoopback() || !networkInterface.isUp()) {
                    continue;
                }
                Enumeration<InetAddress> addresses = networkInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress inetAddress = addresses.nextElement();
                    // 过滤掉IPv6地址，只显示IPv4地址
                    if (inetAddress.getAddress().length == 4) {
                        System.out.println(networkInterface.getName() + ": " + inetAddress.getHostAddress());
                        return inetAddress.getHostAddress();
                    }
                }
            }
        } catch (SocketException e) {
            System.out.println("Error getting network interfaces: " + e.getMessage());
            e.printStackTrace();
        }
        return "";
    }

    @Scheduled(fixedRate = 60000)
    public void loginoutStatus() {
        boolean flag = true;
        System.out.println("---------------------每60s执行一次定时任务---------------------");
        try {
            String command = "cmd.exe /c netstat -n | findstr :3389";
            Process process = Runtime.getRuntime().exec(command);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.contains("ESTABLISHED")) {
                    String[] parts = line.split("\\s+");
                    for(String s : parts) {
                        System.out.println(s);
                    }
                    String remoteAddress = parts[3]; // 通常连接的IP和端口在第3部分，如 192.168.1.4:3389
                    System.out.println("remoteAddress:" + remoteAddress.toString());
                    System.out.println("远程桌面连接来自IP: " + remoteAddress.split(":")[0]);
                    // 获取本机的IP地址3
                    // 如果如果用户登出的话 则修改密码
                    if(StringUtils.isNotBlank(remoteAddress.split(":")[0])) {
                        System.out.println("--------------用户正在使用中--------------");
                        flag = false;
                        // 将远程ip写入map
                        map.put("remoteIP", remoteAddress.split(":")[0]);
                        // remote 和 host
                        HostInfo hostInfo = new HostInfo();
//                        hostInfo.setHostaddress(getHostAddress());
//                        hostInfo.setRemoteaddress(remoteAddress.split(":")[0]);
//                        System.out.println(JSON.toJSONString(hostInfo));
//                        HttpClientUtil.doPost("http://192.168.2.88:8082/ippassword/saveorupdate", JSON.toJSONString(hostInfo));

                        hostInfo.setHostaddress(remoteAddress.split(":")[0]);
                        hostInfo.setRemoteaddress(getHostAddress());
                        System.out.println(JSON.toJSONString(hostInfo));
                        HttpClientUtil.doPost(URL+"/remotepassword/updatePassword", JSON.toJSONString(hostInfo));
                    }
                }
            }
            process.waitFor();
            if(flag) {
                System.out.println("--------------用户已登出--------------");
                // 修改密码并发送
                HostInfo hostInfo = new HostInfo();
//                hostInfo.setHostaddress(getHostAddress());
//                hostInfo.setRemoteaddress("");
                hostInfo.setHostaddress("");
                hostInfo.setRemoteaddress(getHostAddress());
                // 修改密码
                String randomStr = generateCustomRandomString();
                String currentUsername = System.getProperty("user.name"); // 获取当前用户名
                System.out.println("currentUsername:" + currentUsername);
                String command2 = "net user " + currentUsername + " " + randomStr; // 替换<newPassword>为新密码，/domain仅在域环境中使用
                System.out.println("command2:" + command2);
                Process process2 = Runtime.getRuntime().exec(command2);
                int exitCode = process2.waitFor();
                if (exitCode == 0) {
                    System.out.println("密码修改成功");
                } else {
                    System.err.println("密码修改失败，错误代码：" + exitCode);
                    // 可以进一步读取错误流以获取具体错误信息
                }
//                hostInfo.setHostpwd(randomStr);
                hostInfo.setRemotePassword(randomStr);

                System.out.println(JSON.toJSONString(hostInfo));
//                HttpClientUtil.doPost("http://192.168.2.88:8082/ippassword/saveorupdate", JSON.toJSONString(hostInfo));

                HttpClientUtil.doPost(URL+"/remotepassword/updatePassword", JSON.toJSONString(hostInfo));
                map.clear();
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
